<template>
    <el-space>
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="startLeaseGrant('')"
        ></el-button>
        <el-input
            placeholder="请输入查询字符"
            clearable
            :prefix-icon="Search"
            v-model="searchPrefix"
        />
        <el-button type="primary" icon="Search" @click="search()"></el-button>
    </el-space>
    <el-table
        stripe
        :data="tableData"
        style="width: 100%">
        <el-table-column fixed prop="name" label="Name"/>
        <el-table-column prop="ttl" label="ttl"/>
        <el-table-column prop="granted_ttl" label="granted_ttl"/>
        <el-table-column prop="keys" label="keys"/>
        <el-table-column fixed="right" label="Operations">
            <template #default="scope">
                <el-button link type="primary" size="small">Edit</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog
        title="Add Lease"
        v-model="leaseGrantDialog"
        width="500"
    >
        <el-form ref="leaseGrantFormRef" :model="leaseGrantForm" :rules="leaseGrantFormRules">
            <el-form-item label="AutoId" >
                <el-switch v-model='leaseGrantForm.auto' @change="handleAutoId"/>
            </el-form-item>
            <el-form-item label="ID" prop="ID">
                <el-input v-model="leaseGrantForm.id" :disabled="leaseGrantForm.idDisabled" placeholder="请保证 ID 唯一"/>
            </el-form-item>
            <el-form-item label="TTL" prop="TTL">
                <el-input v-model="leaseGrantForm.ttl" placeholder="单位: 秒"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <el-button @click="leaseGrantDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmLeaseGrant">确定</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import {defineProps, onMounted, ref} from "vue";
import {ElMessage} from 'element-plus'
import {Search} from "@element-plus/icons-vue";
import {auth_user_grant, auth_authenticate, lease_leases,lease_grant} from "@/api/etcd3.js"
import {lease_ttl} from "../../api/etcd3.js";
import {Base64} from "js-base64";

const props = defineProps({
    connect: {
        type: Object,
        default: {
            name: '默认标题',
            url: 'http://127.0.0.1:2379',
            version: 'v2',
            username: 'root',
            password: '123456'
        }
    }
})

const tableData = ref([
    {
        name: 'Tom',
        ttl: '123',
        granted_ttl:'1234',
        keys: [],
    }
])

const handleClick = () => {
    console.log('click')
}

// 用户授权
const leaseGrantDialog = ref(false);
const leaseGrantFormRef = ref(null)
const leaseGrantForm = ref({
    auto: false,
    id: 0,
    idDisabled:false,
    ttl: 0
})

const leaseGrantFormRules = ref({
    id: [
        {required: true, message: 'Please input ID', trigger: 'blur'},
        {min: 1, message: 'Length should be greater than 1', trigger: 'blur'},
    ],
    ttl: [
        {required: true, message: 'Please input TTL', trigger: 'blur'},
        {min: 1, message: 'Length should be greater than 1', trigger: 'blur'},
    ],
})

function startLeaseGrant() {
    leaseGrantDialog.value = true;
    leaseGrantForm.value.id = null;
    leaseGrantForm.value.ttl = null;
}

function handleAutoId(value){
    if(value){
        leaseGrantForm.value.id = 0;
        leaseGrantForm.value.idDisabled = true;
    }else{
        leaseGrantForm.value.id = null;
        leaseGrantForm.value.idDisabled = false;
    }
}

function confirmLeaseGrant() {
    leaseGrantFormRef.value.validate((valid) => {
        if (valid) {
            // 关闭弹框
            leaseGrantDialog.value = false;
            // 执行新增逻辑
            let grant = {
                ID: leaseGrantForm.value.id,
                TTL: leaseGrantForm.value.ttl,
            };

            let url = props.connect.url;
            lease_grant(url, grant)
                .then(res => {
                    ElMessage.success('lease_grant ' + 'success');
                    // 重新查询
                    search();
                })
                .catch(error => {
                    let message = error.response.data.message;
                    ElMessage.error('lease_grant ' + message);
                });

        }
    });
}

const searchPrefix = ref('')
function search() {
    let url = props.connect.url;
    lease_leases(url)
        .then(res => {
            console.log(res);
            tableData.value = [];
            let users = [];
            let nodes = res.data.leases;
            if (Array.isArray(nodes)) {
                for (let i = 0; i < nodes.length; i++) {
                    let u = {};
                    u.name = nodes[i].ID;
                    u.roles = [];
                    if(!!searchPrefix.value){
                        if(u.name.includes(searchPrefix.value)){
                            users.push(u);
                        }else{
                            continue;
                        }
                    }else{
                        users.push(u);
                    }
                }
                users.sort((a, b) => {
                    return a.name.localeCompare(b.name);
                });
                tableData.value = users;
                searchTtl();
            }
        })
        .catch(error => {
            let message = error.response.data.message;
            ElMessage.error('lease_leases ' + message);
        })
}

function searchTtl(id){
    let url = props.connect.url;
    if(tableData.value && Array.isArray(tableData.value)){
        for (let index = 0; index < tableData.value.length; index++) {
            let row = tableData.value[index];
            lease_ttl(url,row.name)
                .then(res=>{
                    let result = res.data;
                    row.ttl = result.TTL;
                    row.granted_ttl = result.grantedTTL;
                    let keys = [];
                    if(Array.isArray(result.keys)){
                        for (let i = 0; i < result.keys.length; i++) {
                            keys.push(Base64.decode(result.keys[i]));
                        }
                    }
                    row.keys = keys;
                    console.log('tableData.value',tableData.value);
                })
                .catch(error=>{
                    let message = error.response.data.message;
                    ElMessage.error('lease_ttl ' + message);
                })
        }
    }
}

onMounted(() => {
    search();
})

</script>